# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.

class ApplicationController < ActionController::Base
  helper :all
  helper_method :current_account_session, :current_account, :require_user, :require_users
  filter_parameter_logging :password, :password_confirmation
  before_filter :current_account

  def permission_denied
    flash[:error] = "Sorry, you are not allowed to access that page."
    redirect_to root_url
  end

  private
    def mobile_platform
      agent = request.headers["User-Agent"]
      @mobile = agent[/[mM]obile/] or agent[/HTC/]
    end
    def current_account_session
      return @current_account_session if defined?(@current_account_session)
      @current_account_session = AccountSession.find
    end

    def current_account
      return @current_account if defined?(@current_account)
      @current_account = current_account_session && current_account_session.record
    end

    def require_account
      unless current_account
        store_location
        flash[:error] = "You must be logged in to access this page"
        redirect_to new_account_session_url
        return false
      end
    end

    def require_no_account
      if current_account
        store_location
        flash[:notice] = "You must be logged out to access this page"
        redirect_back_or_default root_path
        return false
      end
    end

    def current_user
      # Questa funzione è richiesta dal modulo per la gestione dei permessi
      return @current_account
    end

    def store_location
      session[:return_to] = request.request_uri
    end

    def redirect_back_or_default(default)
      redirect_to(session[:return_to] || default)
      session[:return_to] = nil
    end
end
